package org.proxycine.gestsalles.model.dao;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.proxycine.gestsalles.model.entities.Film;
import org.proxycine.gestsalles.model.entities.GenreFilm;

public final class CatalogueDao extends Adapter {
	
	private static CatalogueDao instance;
	
	private CatalogueDao() {
		instance = this;
	}
	
	public static CatalogueDao getInstance() {
		if(instance == null)
			instance = new CatalogueDao();
		
		return instance;
	}
	
	public List<Film> getFilmsCatalogue() {
		List<Film> films = new ArrayList<Film>();
		
		try {
			films.addAll(chargerFilms());
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return films;
	}
	
	public List<Film> chargerFilms() throws JSONException, IOException
	{
		JSONObject jRoot = null;
		List<Film> films = new ArrayList<Film>();
		
		
		try {

			jRoot = new JSONObject(getText("http://nyphel.com/~neoz/catalogue.json"));
			//jRoot = new JSONObject(readFile("/home/neoz/workspaces/workspaceM2/gestsalles/GestSalles/WebContent/resources/catalogue/catalogue.json"));
		} catch (Exception e) {
			e.printStackTrace();
		}		
		
		JSONArray jFilms = jRoot.getJSONArray("films");
		
		// Recuperation de tous les films
		for (int i = 0; i < jFilms.length(); i++) {
			try {
				// Creation d'un objet qui contient le film courant	
				JSONObject jFilm = jFilms.getJSONObject(i);
				
				int id = jFilm.getInt("id");
				String titre = jFilm.getString("titre");
				String synopsis = jFilm.getString("synopsis");
				int duree = jFilm.getInt("duree");
				String genre = jFilm.getString("genre");
				String dateSortie = jFilm.getString("dateSortie");
				String nationalite = jFilm.getString("nationalite");
				String realisateur = jFilm.getString("realisateur");
				String acteurs = jFilm.getString("acteurs");
				double rating = jFilm.getDouble("rating");
								
				Date date = null;
				try {
					DateFormat formatter;
					formatter = new SimpleDateFormat("yyyy/MM/dd");
					date = formatter.parse(dateSortie);
				} catch (ParseException e) {
					System.out.println("Exception : "+e);
				}
				
				films.add(new Film(id, titre, synopsis, duree, GenreFilm.valueOf(genre), date, nationalite, realisateur, acteurs, rating));
				
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		
		return films;
	}
	
	public static String getText(String url) throws Exception {
        URL website = new URL(url);
        URLConnection connection = website.openConnection();
        BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                    connection.getInputStream()));

        StringBuilder response = new StringBuilder();
        String inputLine;

        while ((inputLine = in.readLine()) != null) 
            response.append(inputLine);

        in.close();

        return response.toString();
    }
	
	public static String readFile(String filepath) throws FileNotFoundException {
		String text = "";
		Scanner scanner = new Scanner(new File(filepath));
		while (scanner.hasNextLine()) {
		    String line = scanner.nextLine();   
		    text += line;
		}
		scanner.close();
		
		return text;
	}
}
